import datetime
import json
import os
from common.log import logger


class BaseConfig:
    def __init__(self):
        # 先设置默认值
        self.APP_NAME: str = 'Kumquat King Robot'
        self.MY_DAD_NN: str = '慌雨'
        
        """Base server configuration"""
        self.WX_TOKEN: str = os.getenv("WX_TOKEN") if os.getenv("WX_TOKEN") else "123456"
        self.WX_ENCODING_AES_KEY: str = os.getenv("WX_ENCODING_AES_KEY") if os.getenv("WX_ENCODING_AES_KEY") else "any"
        self.WX_CORP_ID: str = os.getenv("WX_CORP_ID") if os.getenv("WX_CORP_ID") else "any"
        self.SERVER_HOST: str = '0.0.0.0'
        self.LOCAL_HOST: str = 'http://127.0.0.1'
        self.SERVER_PORT: int = 8555
        self.ROOT_PATH: str = os.path.dirname(__file__)

        """OTHERS"""
        self.MINIO_BUCKET_NAME: str = os.getenv("MINIO_BUCKET_NAME") if os.getenv("MINIO_BUCKET_NAME") else "kqk-bucket"
        self.DEFAULT_DATE_FORMAT: str = '%Y-%m-%d'
        self.DEFAULT_TIME_FORMAT: str = self.DEFAULT_DATE_FORMAT + ' %H:%M:%S'
        self.FILE_GEN_TIME_FORMAT: str = '%Y%m%d%H%M%S'
        self.PACKAGE_DEADLINE_TIME: datetime.datetime = datetime.datetime.combine(
            datetime.datetime.now().date(), datetime.datetime.min.time().replace(hour=14))  # 装果截至时间
        self.PACKAGE_DEADLINE_ON: bool = False  # 打包截止时间, debug 用, 生产环境需要改为True
        self.DEV_NGROK_URL: str = "https://48dbc6486c3b.ngrok-free.app"

        """DB Connection configuration"""
        self.DB_NAME: str = 'kumquat_king_robot.db'
        self.DATABASE_URL: str = 'sqlite:///instance/' + self.DB_NAME
        self.DB_POOL_SIZE: int = 20
        
        # 从配置文件加载并覆盖默认值
        config_data = EnvConfig.load_config()
        if config_data:
            for key, value in config_data.items():
                setattr(self, key, value)

class EnvConfig:
    """
    Wechat default environment config
    """

    def __init__(self):
        pass

    @staticmethod
    def load_config() -> dict | None:
        try:
            config_path = ['./config.json', '../config.json']
            for path in config_path:
                if os.path.exists(path):
                    with open(path, 'r', encoding='utf-8') as f:
                        config_str = f.read()
                    res_config = json.loads(config_str)
                    for name, value in os.environ.items():
                        name = name.upper()
                        if name in res_config:
                            try:
                                res_config[name] = eval(value)
                            except:
                                if value == "false":
                                    res_config[name] = False
                                elif value == "true":
                                    res_config[name] = True
                                else:
                                    res_config[name] = value
                            logger.info(f"[config] Override the config by env conf {name}={value}")
                    # logger.info("[INIT] Load config: {}".format(res_config))
                    return res_config
        except Exception as e:
            logger.critical("[config] Failed to load config json file, or path not exists. Process exit.")
            logger.critical(e)
            exit(1)


env_config = EnvConfig()
base_config = BaseConfig()